/**
 *
 */
package com.bsoft.gol.hcb.service.evaluation;

import com.bsoft.gol.hcb.dao.evaluation.BaseEvaluationDefineDAO;
import com.bsoft.gol.hcb.dao.evaluation.BaseEvaluationItemDAO;
import com.bsoft.gol.hcb.dao.evaluation.BaseEvaluationLabelDAO;
import com.bsoft.gol.hcb.dao.evaluation.BaseEvaluationRecordDAO;
import com.bsoft.gol.hcb.utils.Constants;
import ctd.controller.exception.ControllerException;
import ctd.net.rpc.Client;
import ctd.spring.boot.annotation.SsdevService;
import ctd.util.annotation.RpcService;
import hcn.enums.EvaluationBusinessTypeEnum;
import hcn.util.CommonUtils;
import hcn.util.RpcUserToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import pcn.bean.sign.BaseEvaluateDto;
import pcn.bean.sign.BaseEvaluationDefineQo;
import pcn.consultation.BaseEvaluationLabel;
import pcn.enums.OperationTypeEmun;
import pcn.sign.BaseEvaluationDefine;
import pcn.sign.BaseEvaluationItem;
import pcn.sign.PcnBaseService;
import pcn.vo.chissign.ChisCompleteServiceVO;
import pcn.vo.sign.BaseEvaluationDefineAndItemsVo;
import pcn.vo.sign.BaseEvaluationDefineVo;
import pcn.vo.sign.BaseEvaluationItemVO;
import pcn.vo.sign.BaseEvaluationLabelVo;
import service.rpc.PcnBaseServiceIntf;
import service.rpc.PcnOperLogServiceIntf;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @since 2017-05-02 11:36:36
 */
@SsdevService("baseEvaluationDefineService")
public class BaseEvaluationDefineServiceImpl{

	private final static Logger LOGGER = LoggerFactory.getLogger(BaseEvaluationRecordServiceImpl.class);

	@Autowired
	private BaseEvaluationDefineDAO baseEvaluationDefineDAO;
	@Autowired
	private BaseEvaluationLabelDAO baseEvaluationLabelDAO;
	@Autowired
	private BaseEvaluationRecordDAO baseEvaluationRecordDAO;
	@Autowired
	private BaseEvaluationItemDAO baseEvaluationItemDAO;

	@Autowired
	private PcnBaseServiceIntf pcnBaseServiceIntf;
	@Autowired
	private PcnOperLogServiceIntf pcnOperLogServiceIntf;
	/**
	 * 查询所有评价模板列表
	 *
	 * @return
	 */
	@RpcService
	public List<BaseEvaluationDefine> findBaseEvaluationDefines() {
		return baseEvaluationDefineDAO.getFirstEvaluationList("1");
	}

	/**
	 * 查询启用评价模板列表
	 *
	 * @return
	 */
	@RpcService
	public List<BaseEvaluationDefine> findEnableEvaluationDefines() {
		return baseEvaluationDefineDAO.getFirstEvaluationList("1");
	}

	/**
	 * 查询评价模板和评价项列表
	 *
	 * @param id
	 * @return
	 */
	@RpcService
	public BaseEvaluationDefineVo queryBaseEvaluationDefineDetail(int id) {
		BaseEvaluationDefineVo baseEvaluationDefineVo = new BaseEvaluationDefineVo();

		BaseEvaluationDefine baseEvaluationDefine = baseEvaluationDefineDAO.getBaseEvaluationDefineById(id);
		if (baseEvaluationDefine != null) {
			//首评
			BaseEvaluationDefine firstDefine = baseEvaluationDefineDAO.getBaseEvaluationDefineByBussinessType(baseEvaluationDefine.getBusinessType(), (byte) 1);
			if(null != firstDefine){
				List<BaseEvaluationItem> list = baseEvaluationItemDAO.getBaseEvaluationItemByDefineId(firstDefine.getId());
				baseEvaluationDefineVo.setFirstDefine(baseEvaluationDefine);
				List<BaseEvaluationItemVO> baseEvaluationItemVOList = new ArrayList<>();
				if (list != null) {
					if (list.size() > 0) {
						BaseEvaluationItemVO item;
						for (BaseEvaluationItem baseEvaluationItem : list) {
							item = new BaseEvaluationItemVO();
							item.setItemId(baseEvaluationItem.getId());
							item.setItemName(baseEvaluationItem.getContent());
							item.setStatus(baseEvaluationItem.getStatus());
							baseEvaluationItemVOList.add(item);
						}
						baseEvaluationDefineVo.setFirstItemList(baseEvaluationItemVOList);
					}
				}

				//标签
				List<BaseEvaluationLabel> labelList = baseEvaluationLabelDAO.findBaseEvaluationLabelByDefineId(id);
				baseEvaluationDefineVo.setLabelList(labelList);
				if(!CollectionUtils.isEmpty(labelList)){
					List<BaseEvaluationLabel> collect = labelList.stream().filter(e -> 1==e.getIsEnable()).collect(Collectors.toList());
					if(CollectionUtils.isEmpty(collect)){
						baseEvaluationDefineVo.setLabelFlag("0");
					}
				}
			}

			//追评
			BaseEvaluationDefine secondDefine = baseEvaluationDefineDAO.getBaseEvaluationDefineByBussinessType(baseEvaluationDefine.getBusinessType(), (byte) 2);
			if (secondDefine != null) {
				List<BaseEvaluationItem> evaluationList = baseEvaluationItemDAO.getBaseEvaluationItemByDefineId(secondDefine.getId());
				baseEvaluationDefineVo.setSecondDefine(secondDefine);
				List<BaseEvaluationItemVO> baseEvaluationItemVOList1 = new ArrayList<>();
				if (evaluationList != null) {
					if (evaluationList.size() > 0) {
						BaseEvaluationItemVO item;
						for (BaseEvaluationItem baseEvaluationItem : evaluationList) {
							item = new BaseEvaluationItemVO();
							item.setItemId(baseEvaluationItem.getId());
							item.setItemName(baseEvaluationItem.getContent());
							item.setStatus(baseEvaluationItem.getStatus());
							baseEvaluationItemVOList1.add(item);
						}
						baseEvaluationDefineVo.setSecondItemList(baseEvaluationItemVOList1);
					}
				}
				//标签
				List<BaseEvaluationLabel> secondLabelList = baseEvaluationLabelDAO.findBaseEvaluationLabelByDefineId(secondDefine.getId());
				baseEvaluationDefineVo.setSecondLabelList(secondLabelList);
				if(!CollectionUtils.isEmpty(secondLabelList)){
					List<BaseEvaluationLabel> collect = secondLabelList.stream().filter(e -> 1==e.getIsEnable()).collect(Collectors.toList());
					if(CollectionUtils.isEmpty(collect)){
						baseEvaluationDefineVo.setSecondLabelFlag("0");
					}
				}
			}
		}
		return baseEvaluationDefineVo;
	}

	/**
	 * 保存评价模板，只保存首评的模板
	 *
	 * @param baseEvaluationDefine
	 * @return
	 */
	@RpcService
	public Integer save(BaseEvaluationDefine baseEvaluationDefine) throws ControllerException {
		baseEvaluationDefine.setTenantId(RpcUserToken.getTenantId());
		//businessType 保存方式1，2....
		//查询名称是否重复
		Long count = baseEvaluationDefineDAO.getBaseEvaluationDefineByBusinessName(baseEvaluationDefine.getBusinessName());
		if (count > 0) {
			return 0;//重复
		}
		//查询出最后一条首评记录
		BaseEvaluationDefine define = baseEvaluationDefineDAO.getLast();
		String businessType = "1";
		if (define != null) {
			businessType = define.getBusinessType();
			//   String typeStr = businessType.substring(2);
			int typeInt = Integer.parseInt(businessType);
			businessType = String.valueOf(typeInt + 1);
		}
		baseEvaluationDefine.setBusinessType(businessType);
		baseEvaluationDefine.setStatus("1");
		baseEvaluationDefine.setAddEvaluationFlag("1");
		baseEvaluationDefine.setContentFlag("1");
		baseEvaluationDefine.setPriorLevel((byte) 1);
		baseEvaluationDefineDAO.save(baseEvaluationDefine);
		//保存到记录表
		pcnOperLogServiceIntf.saveInfo(baseEvaluationDefine.getBusinessName(), OperationTypeEmun.add.getName(),baseEvaluationDefine.getId().toString(),"系统配置-评价管理");
		return baseEvaluationDefine.getId();
	}

	/**
	 * 评价模板设置
	 *
	 * @param baseEvaluateDto
	 * @return
	 */
	@RpcService
	public Integer updateBaseEvaluationDefineAndItem(BaseEvaluateDto baseEvaluateDto) throws ControllerException {
		if(null == baseEvaluateDto.getDefine()){
			throw new ControllerException("评价定义不能为空");
		}
		//如果id为空，则是追评设置第一次提交
		BaseEvaluationDefine de = baseEvaluationDefineDAO.getBaseEvaluationDefineByBussinessType(baseEvaluateDto.getDefine().getBusinessType(), (byte) 2);
		if (CommonUtils.isNull(baseEvaluateDto.getDefine().getId())) {
			//判断bussinessType是否已经存在
			if (de == null) {
				BaseEvaluationDefine baseEvaluationDefine = new BaseEvaluationDefine();
				baseEvaluationDefine.setBusinessType(baseEvaluateDto.getDefine().getBusinessType());
				baseEvaluationDefine.setBusinessName(baseEvaluateDto.getDefine().getBusinessName());
				baseEvaluationDefine.setStatus("1");
				baseEvaluationDefine.setTenantId(RpcUserToken.getTenantId());
				baseEvaluationDefine.setContentFlag(baseEvaluateDto.getDefine().getContentFlag());
				baseEvaluationDefine.setPriorLevel((byte) 2);
				baseEvaluationDefineDAO.save(baseEvaluationDefine);
				baseEvaluateDto.getDefine().setId(baseEvaluationDefine.getId());
			} else {
				baseEvaluateDto.getDefine().setId(de.getId());
			}
		}
		if (de != null) {

			baseEvaluationDefineDAO.updateBussinessName(baseEvaluateDto.getDefine().getBusinessName(), de.getId());
		}

		baseEvaluationDefineDAO.updateEvaluationDefaine(baseEvaluateDto.getDefine());
		List<BaseEvaluationItemVO> list = baseEvaluateDto.getItemList();
		if (list != null) {
			BaseEvaluationItem baseEvaluationItem;
			for (BaseEvaluationItemVO baseEvaluationItemVO : list) {
				//如果不为空，修改
				if (baseEvaluationItemVO.getItemId() > 0) {
					BaseEvaluationItem baseEvaluationItem1 = baseEvaluationItemDAO.getBaseEvaluationItemByIdAndDefineId(baseEvaluationItemVO.getItemId(), baseEvaluateDto.getDefine().getId());
					//判断itemId和模板ID传的情况。数据是否存在
					if (baseEvaluationItem1 != null) {
						baseEvaluationItemDAO.updateById(baseEvaluationItemVO.getItemId(), baseEvaluationItemVO.getItemName(), baseEvaluationItemVO.getStatus());
					} else {
						//通过itemId去判断下是否存在
						BaseEvaluationItem baseEvaluationItem2 = baseEvaluationItemDAO.getBaseEvaluationItemById(baseEvaluationItemVO.getItemId());
						if (baseEvaluationItem2 != null) {
							baseEvaluationItemDAO.updateById(baseEvaluationItemVO.getItemId(), baseEvaluationItemVO.getItemName(), baseEvaluationItemVO.getStatus());
						} else {
							//如果为空，进行保存
							baseEvaluationItem = new BaseEvaluationItem();
							baseEvaluationItem.setDefineId(baseEvaluateDto.getDefine().getId());
							baseEvaluationItem.setContent(baseEvaluationItemVO.getItemName());
							baseEvaluationItem.setTenantId(RpcUserToken.getTenantId());
							baseEvaluationItem.setStatus(baseEvaluationItemVO.getStatus());
							baseEvaluationItem.setIsEnable(1);
							baseEvaluationItemDAO.save(baseEvaluationItem);
						}
					}
				} else {
					//如果为空，进行保存
					baseEvaluationItem = new BaseEvaluationItem();
					baseEvaluationItem.setDefineId(baseEvaluateDto.getDefine().getId());
					baseEvaluationItem.setContent(baseEvaluationItemVO.getItemName());
					baseEvaluationItem.setTenantId(RpcUserToken.getTenantId());
					baseEvaluationItem.setStatus(baseEvaluationItemVO.getStatus());
					baseEvaluationItem.setIsEnable(1);
					baseEvaluationItemDAO.save(baseEvaluationItem);
				}
			}
		}

		//保存标签
		List<BaseEvaluationLabelVo> labelVos = baseEvaluateDto.getLabelList();
		if (labelVos != null) {
			BaseEvaluationLabel baseEvaluationLabel;
			for (BaseEvaluationLabelVo labelVo : labelVos) {
				if("0".equals(baseEvaluateDto.getLabelFlag())){
					labelVo.setIsEnable((byte)0);
				}else {
                    labelVo.setIsEnable((byte)1);
                }
				//如果不为空，修改
				if (labelVo.getId() > 0) {
					BaseEvaluationLabel baseEvaluationLabel1 = baseEvaluationLabelDAO.get(labelVo.getId());
					//判断itemId和模板ID传的情况。数据是否存在
					if (baseEvaluationLabel1 != null) {
						baseEvaluationLabel1.setContent(labelVo.getContent());
						baseEvaluationLabel1.setIsEnable(labelVo.getIsEnable());
						baseEvaluationLabelDAO.update(baseEvaluationLabel1);
					} else {
						//如果为空，进行保存
						BaseEvaluationLabel baseEvaluationLabel2 = new BaseEvaluationLabel();
						baseEvaluationLabel2.setDefineId(baseEvaluateDto.getDefine().getId());
						baseEvaluationLabel2.setContent(labelVo.getContent());
						baseEvaluationLabel2.setTenantId(RpcUserToken.getTenantId());
						baseEvaluationLabel2.setIsEnable(labelVo.getIsEnable());
						baseEvaluationLabelDAO.save(baseEvaluationLabel2);
					}
				}else {
					//如果为空，进行保存
					BaseEvaluationLabel baseEvaluationLabel2 = new BaseEvaluationLabel();
					baseEvaluationLabel2.setDefineId(baseEvaluateDto.getDefine().getId());
					baseEvaluationLabel2.setContent(labelVo.getContent());
					baseEvaluationLabel2.setTenantId(RpcUserToken.getTenantId());
					baseEvaluationLabel2.setIsEnable(labelVo.getIsEnable());
					baseEvaluationLabelDAO.save(baseEvaluationLabel2);
				}
			}
		}
		return baseEvaluateDto.getDefine().getId();
	}

	@RpcService
	public BaseEvaluationDefineAndItemsVo queryEvaluationDefineAndItemsByBussinessType(BaseEvaluationDefineQo qo) {
		BaseEvaluationDefineAndItemsVo baseEvaluationDefineVo = new BaseEvaluationDefineAndItemsVo();
		PcnBaseService pcnBaseService = pcnBaseServiceIntf.getPcnBaseServiceById(qo.getServiceId());
		BaseEvaluationDefine baseEvaluationDefine = null;


		Byte priorLevel = (byte) 1;

		if (pcnBaseService != null) {
			//首评还是追评
			String userId = CommonUtils.isEmpty(qo.getUserId()) ? RpcUserToken.getUserId() : qo.getUserId();
			Long count = baseEvaluationRecordDAO.getCountByUserIdAndBusinessId(userId, qo.getBusinessId());
			priorLevel = count > 0 ? (byte) 2 : (byte) 1;
			if (pcnBaseService.getEvaluationTplId() == null) {
				return baseEvaluationDefineVo;
			}
			//查询启用的评价模板
			baseEvaluationDefine = baseEvaluationDefineDAO.getBaseEvaluationDefineByIdAndStatus(pcnBaseService.getEvaluationTplId());
		}else{
			priorLevel = qo.getPriorLevel();
			//获取评价业务类型
			if(EvaluationBusinessTypeEnum.SIGN.getTypeCode().equals(qo.getBusinessType())){
				try {
					List<ChisCompleteServiceVO> chisCompleteServiceVOList = (List<ChisCompleteServiceVO>) Client.rpcInvoke("pcn.pcnSignPackService", "queryChisCompleteService", qo.getBusinessId());;
					if(CommonUtils.isNotEmpty(chisCompleteServiceVOList) && Constants.TWO.toString().equals(chisCompleteServiceVOList.get(0).getEvaluationCategory())){
						priorLevel = (byte) 1;
					}
				} catch (Throwable throwable) {
					LOGGER.info("查询公卫服务记录失败", throwable.getMessage());
				}
			}
			//若本地无服务项，根据业务类型查询启用的模板（包括家医融合，默认查询家医评价类型）
			baseEvaluationDefine = baseEvaluationDefineDAO.getBaseEvaluationDefineByBussinessTypeAndStatus(qo.getBusinessType(), priorLevel);
		}

		if (baseEvaluationDefine != null) {
			//查询启用的评价项
			List<BaseEvaluationItem> list = baseEvaluationItemDAO.findBaseEvaluationItemByDefineIdAndStatus(baseEvaluationDefine.getId());
			baseEvaluationDefineVo.setId(baseEvaluationDefine.getId());
			baseEvaluationDefineVo.setBusinessName(baseEvaluationDefine.getBusinessName());
			baseEvaluationDefineVo.setPriorLevel(baseEvaluationDefine.getPriorLevel());
			baseEvaluationDefineVo.setAddEvaluationFlag(baseEvaluationDefine.getAddEvaluationFlag());
			baseEvaluationDefineVo.setBusinessType(baseEvaluationDefine.getBusinessType());
			baseEvaluationDefineVo.setContentFlag(baseEvaluationDefine.getContentFlag());
			baseEvaluationDefineVo.setStatus(baseEvaluationDefine.getStatus());
			baseEvaluationDefineVo.setOccasion(baseEvaluationDefine.getOccasion());
			List<BaseEvaluationItemVO> baseEvaluationItemVOList = new ArrayList<>();
			if (CommonUtils.isNotEmpty(list)) {
				BaseEvaluationItemVO item;
				for (BaseEvaluationItem baseEvaluationItem : list) {
					item = new BaseEvaluationItemVO();
					item.setItemId(baseEvaluationItem.getId());
					item.setItemName(baseEvaluationItem.getContent());
					baseEvaluationItemVOList.add(item);
				}
				baseEvaluationDefineVo.setItemList(baseEvaluationItemVOList);
			}

			List<BaseEvaluationLabel> baseEvaluationItems = baseEvaluationLabelDAO.findBaseEvaluationLabelByDefineId(baseEvaluationDefine.getId());
			List<BaseEvaluationLabelVo> baseEvaluationLabelVoList = new ArrayList<>();
			if (CommonUtils.isNotEmpty(baseEvaluationItems)) {
				BaseEvaluationLabelVo baseEvaluationLabelVo;
				for (BaseEvaluationLabel baseEvaluationLabel : baseEvaluationItems) {
					baseEvaluationLabelVo = new BaseEvaluationLabelVo();
					baseEvaluationLabelVo.setId(baseEvaluationLabel.getId());
					baseEvaluationLabelVo.setContent(baseEvaluationLabel.getContent());
					baseEvaluationLabelVoList.add(baseEvaluationLabelVo);
				}
				baseEvaluationDefineVo.setLabelList(baseEvaluationLabelVoList);
			}
            if(!CollectionUtils.isEmpty(baseEvaluationItems)){
                List<BaseEvaluationLabel> collect = baseEvaluationItems.stream().filter(e -> 1==e.getIsEnable()).collect(Collectors.toList());
                if(CollectionUtils.isEmpty(collect)){
                    baseEvaluationDefineVo.setLabelFlag("0");
                }
            }
		}
		return baseEvaluationDefineVo;
	}

	@RpcService
	public Long queryEvaluationStatusByBussinessType(BaseEvaluationDefineQo qo) {
		//首评还是追评
		Long count = baseEvaluationRecordDAO.getCountByUserIdAndBusinessIdAndType(RpcUserToken.getUserId(), qo.getBusinessId(),qo.getBusinessType());
		if (count == null){
			return 0L;
		}else{
			return count;
		}
	}

	/**
	 * 获取评价记录
	 *
	 * @param evaluationTplId
	 * @return
	 */
	@RpcService
	public BaseEvaluationDefine getBaseEvaluationDefineByIdAndStatus(Integer evaluationTplId) {
		return baseEvaluationDefineDAO.getBaseEvaluationDefineByIdAndStatus(evaluationTplId);
	}
	@RpcService
	public void deleteBaseEvaluationDefineAndItem(int itemId) {
		baseEvaluationItemDAO.updateIsEnableById(itemId);
	}
}